package top.xxyu.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import top.xxyu.config.SendEmail;
import top.xxyu.dao.MailMessageDao;
import top.xxyu.dao.UserMailDao;
import top.xxyu.entity.MailMessage;
import top.xxyu.entity.UserMail;

import java.text.SimpleDateFormat;
import java.util.List;

public class JobMail implements Job {
    @Autowired
    private UserMailDao userMailDao;
    @Autowired
    private MailMessageDao mailMessageDao;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("jobMail：启动任务=======================");
        List<MailMessage> mailMessageList = mailMessageDao.findAll();
        mailMessageList.forEach(mailMessage -> {
            UserMail mailInfo = new UserMail();
            mailInfo.setUserMail(mailMessage.getFromUser());
            ExampleMatcher exampleMatcher = ExampleMatcher
                    .matching()
                    .withMatcher("userMail", ExampleMatcher.GenericPropertyMatchers.exact());
            if (userMailDao.exists(Example.of(mailInfo, exampleMatcher))) {
                mailInfo = userMailDao.findOne(Example.of(mailInfo, exampleMatcher)).get();
                int status = mailMessage.getStatus();
                if(0 == status){
                    mailMessage.setFromUserMail(mailInfo);
                    boolean send = SendEmail.send(mailMessage);
                    if (send){
                        mailMessage.setStatus(1);
                        mailMessageDao.save(mailMessage);
                    }
                    mailInfo = null;
                }


            }
        });
        System.out.println("jobMail：下次执行时间====="+
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(jobExecutionContext.getNextFireTime())+"==============");

    }
}
